package com.quectel.cms.controller.workorder;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.workorder.WorkOrderDirectConfVo;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.core.module.workorder.dto.WorkOrderDirectDto;
import com.quectel.core.module.workorder.service.WorkOrderDirectService;
import com.quectel.sys.module.sys.dto.SysCodeDto;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/03/09 13:38
 */
@RestController
@RequestMapping("workOrderDirect")
@Tag(name = "WorkOrderDirectController", description = "工单引用相关api")
public class WorkOrderDirectController extends BaseController {

    @DubboReference
    private WorkOrderDirectService workOrderDirectService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private DeptPersonService deptPersonService;


    /**
     * 设置定向处理人
     *
     * @param workOrderDirectConfVo
     * @return
     */
    @PostMapping("configure")
    @RequirePermissions(values = "workOrderDirect:edit")
    @Operation(summary = "设置工单定向处理人")
    public Response<Page<WorkOrderDirectDto>> configure(@RequestBody @Validated WorkOrderDirectConfVo workOrderDirectConfVo) {
        if (Objects.isNull(workOrderDirectConfVo.getDeptPersonId())) {
            WorkOrderDirectDto oldDto = workOrderDirectService.selectOne(workOrderDirectConfVo.getVillageId(), workOrderDirectConfVo.getCategory(), workOrderDirectConfVo.getType());
            if (Objects.isNull(oldDto)) {
                return Response.error("不存在该配置，无需关闭处理人");
            }

            workOrderDirectService.deleteById(oldDto.getId());
        } else {
            VillageDto villageDto = villageService.selectCacheById(workOrderDirectConfVo.getVillageId());
            if (Objects.isNull(villageDto)) {
                return Response.error("小区不存在");
            }
            DeptPersonDto personDto = deptPersonService.selectCacheById(workOrderDirectConfVo.getDeptPersonId());
            if (Objects.isNull(personDto)) {
                return Response.error("处理人不存在");
            }
            if (!workOrderDirectConfVo.getVillageId().equals(personDto.getVillageId())) {
                return Response.error("处理人不属于该小区");
            }

            // 是否已经存在了，替换下
            WorkOrderDirectDto oldDto = workOrderDirectService.selectOne(workOrderDirectConfVo.getVillageId(), workOrderDirectConfVo.getCategory(), workOrderDirectConfVo.getType());
            if (oldDto == null) {
                WorkOrderDirectDto newlyDto = new WorkOrderDirectDto();
                newlyDto.setTenantId(villageDto.getTenantId());
                newlyDto.setVillageId(villageDto.getId());
                newlyDto.setCategory(workOrderDirectConfVo.getCategory());
                newlyDto.setType(workOrderDirectConfVo.getType());
                newlyDto.setDeptPersonId(workOrderDirectConfVo.getDeptPersonId());
                newlyDto.setStatus(SystemConstants.ENABLE);
                fillSaveCommonData(newlyDto);
                workOrderDirectService.save(newlyDto);
            } else {
                WorkOrderDirectDto updateDto = new WorkOrderDirectDto();
                updateDto.setId(oldDto.getId());
                updateDto.setDeptPersonId(workOrderDirectConfVo.getDeptPersonId());
                workOrderDirectService.updateById(updateDto);
            }
        }
        return Response.ok();
    }


    /**
     * 定向配置完整列表
     *
     * @param villageId
     * @param category
     * @param type
     * @return
     */
    @GetMapping("confList")
    @RequirePermissions(values = "workOrderDirect:list")
    @Operation(summary = "根据参数查询工单引用完整列表")
    public Response<Page<WorkOrderDirectDto>> confList(
            @Parameter(description = "小区id", required = true) @RequestParam Long villageId,
            @Parameter(description = "工单种类") @RequestParam(required = false) Byte category,
            @Parameter(description = "工单类型") @RequestParam(required = false) Byte type
    ) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        super.fillAuthorityData(request.getParams());

        List<WorkOrderDirectDto> workOrderDirectDtos = workOrderDirectService.queryList(request.getParams());
        Map<String, WorkOrderDirectDto> directConfMap = new HashMap<>();
        for (WorkOrderDirectDto workOrderDirectDto : workOrderDirectDtos) {
            directConfMap.put(workOrderDirectDto.getCategory() + "_" + workOrderDirectDto.getType(), workOrderDirectDto);
        }

        List<SysCodeDto> categoryCodeList = SysCodeUtils.easyToGetByMark(SysCodeKeyConstants.WORK_ORDER_CATEGORY);

        List<WorkOrderDirectDto> result = new ArrayList<>();
        for (SysCodeDto categoryCode : categoryCodeList) {
            if (Objects.nonNull(category) && !category.equals(Byte.valueOf(categoryCode.getValue()))) {
                continue;
            }
            if (CollectionUtils.isNotEmpty(categoryCode.getChildren())) {
                for (SysCodeDto typeCode : categoryCode.getChildren()) {
                    if (Objects.nonNull(type) && !type.equals(Byte.valueOf(typeCode.getValue()))) {
                        continue;
                    }
                    WorkOrderDirectDto workOrderDirectDto = directConfMap.get(categoryCode.getValue() + "_" + typeCode.getValue());
                    if (Objects.isNull(workOrderDirectDto)) {
                        workOrderDirectDto = new WorkOrderDirectDto();
                        workOrderDirectDto.setVillageId(villageId);
                        VillageDto villageDto = villageService.selectCacheById(villageId);
                        workOrderDirectDto.setVillage(villageDto);
                        workOrderDirectDto.setTenantId(Objects.nonNull(villageDto) ? villageDto.getTenantId() : null);
                        workOrderDirectDto.setCategory(Byte.valueOf(categoryCode.getValue()));
                        workOrderDirectDto.setType(Byte.valueOf(typeCode.getValue()));
                        workOrderDirectDto.setStatus(SystemConstants.DISABLE);
                    }
                    result.add(workOrderDirectDto);
                }
            }
        }

        Page<WorkOrderDirectDto> page = new Page<>(1, result.size(), result.size(), result);
        return Response.<Page<WorkOrderDirectDto>>ok().wrap(page);
    }

    /**
     * 根据参数分页查询工单引用列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "workOrderDirect:list")
    @Operation(summary = "根据参数分页查询工单引用列表")
    public Response<Page<WorkOrderDirectDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        super.fillAuthorityData(request.getParams());
        int total = workOrderDirectService.queryTotal(request.getParams());

        List<WorkOrderDirectDto> list = null;
        if (total > 0) {
            list = workOrderDirectService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<WorkOrderDirectDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<WorkOrderDirectDto>>ok().wrap(page);
    }

    /**
     * 根据id查询工单引用列表，编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "workOrderDirect:edit")
    @Operation(summary = "根据id查询工单引用列表，编辑查询反显")
    public Response<WorkOrderDirectDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (workOrderDirectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        WorkOrderDirectDto workOrderDirectDto = workOrderDirectService.selectById(id);

        return Response.<WorkOrderDirectDto>ok().wrap(workOrderDirectDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "workOrderDirect:info")
    @Operation(summary = "根据id查询工单引用列表")
    public Response<WorkOrderDirectDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (workOrderDirectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        WorkOrderDirectDto workOrderDirectDto = workOrderDirectService.selectById(id);

        return Response.<WorkOrderDirectDto>ok().wrap(workOrderDirectDto);
    }

    /**
     * 保存工单引用记录
     *
     * @param workOrderDirectDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "workOrderDirect:edit")
    @Operation(summary = "保存工单引用记录")
    public Response<Object> save(@RequestBody @Validated WorkOrderDirectDto workOrderDirectDto) {

        //填充基础数据
        fillSaveCommonData(workOrderDirectDto);

        workOrderDirectService.save(workOrderDirectDto);

        return Response.ok();
    }


    /**
     * 修改工单引用记录
     *
     * @param workOrderDirectDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "workOrderDirect:edit")
    @Operation(summary = "修改工单引用记录")
    public Response<Object> update(@RequestBody @Validated WorkOrderDirectDto workOrderDirectDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(workOrderDirectDto.getId()));
        if (workOrderDirectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(workOrderDirectDto);

        workOrderDirectService.updateById(workOrderDirectDto);

        return Response.ok();
    }

    /**
     * 批量删除工单引用记录
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "workOrderDirect:delete")
    @Operation(summary = "批量删除工单引用记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (workOrderDirectService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        workOrderDirectService.deleteBatch(ids);

        return Response.ok();
    }
}
